import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface Doctor {
  id: string
  name: string
  gender: '男' | '女'
  age: number
  phone: string
  email: string
  avatar: string
  title: '主任医师' | '副主任医师' | '主治医师' | '住院医师' | '医师'
  department: string
  departmentId: string
  specialty: string[]
  education: string
  experience: number
  status: '在职' | '休假' | '离职'
  schedules: {
    day: string
    timeSlots: Array<{
      start: string
      end: string
      available: boolean
      maxPatients: number
      currentPatients: number
    }>
  }[]
  qualifications: string[]
  achievements: string[]
  patientCount: number
  rating: number
  introduction: string
  joinDate: string
}

export const useDoctorStore = defineStore('doctor', () => {
  const doctors = ref<Doctor[]>([
    {
      id: 'D001',
      name: '王医生',
      gender: '男',
      age: 45,
      phone: '13900139001',
      email: 'wang.doctor@hospital.com',
      avatar: '/avatars/doctor1.jpg',
      title: '主任医师',
      department: '内分泌科',
      departmentId: 'DEPT001',
      specialty: ['糖尿病', '甲状腺疾病', '内分泌失调'],
      education: '医学博士',
      experience: 20,
      status: '在职',
      schedules: [
        {
          day: '周一',
          timeSlots: [
            { start: '08:00', end: '12:00', available: true, maxPatients: 20, currentPatients: 15 },
            { start: '14:00', end: '17:00', available: true, maxPatients: 15, currentPatients: 8 }
          ]
        }
      ],
      qualifications: ['执业医师证', '内分泌专科医师证', '糖尿病专家认证'],
      achievements: ['优秀医师奖', '科研成果奖'],
      patientCount: 1256,
      rating: 4.8,
      introduction: '从事内分泌临床工作20年，擅长糖尿病、甲状腺疾病的诊治。',
      joinDate: '2004-03-15'
    }
  ])

  const currentDoctor = ref<Doctor | null>(null)
  const searchQuery = ref('')
  const filterDepartment = ref('')
  const filterTitle = ref('')
  const loading = ref(false)

  // 获取医生列表
  const getDoctors = async (params?: any) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      return doctors.value
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取医生
  const getDoctorById = (id: string) => {
    return doctors.value.find(d => d.id === id)
  }

  // 根据科室获取医生
  const getDoctorsByDepartment = (departmentId: string) => {
    return doctors.value.filter(d => d.departmentId === departmentId && d.status === '在职')
  }

  // 添加医生
  const addDoctor = async (doctor: Omit<Doctor, 'id' | 'joinDate' | 'patientCount' | 'rating'>) => {
    loading.value = true
    try {
      const newDoctor: Doctor = {
        ...doctor,
        id: `D${Date.now()}`,
        joinDate: new Date().toISOString().split('T')[0],
        patientCount: 0,
        rating: 5.0
      }
      doctors.value.unshift(newDoctor)
      return newDoctor
    } finally {
      loading.value = false
    }
  }

  // 更新医生信息
  const updateDoctor = async (id: string, updates: Partial<Doctor>) => {
    loading.value = true
    try {
      const index = doctors.value.findIndex(d => d.id === id)
      if (index > -1) {
        doctors.value[index] = { ...doctors.value[index], ...updates }
        return doctors.value[index]
      }
      throw new Error('医生不存在')
    } finally {
      loading.value = false
    }
  }

  // 删除医生
  const deleteDoctor = async (id: string) => {
    loading.value = true
    try {
      const index = doctors.value.findIndex(d => d.id === id)
      if (index > -1) {
        doctors.value.splice(index, 1)
        return true
      }
      return false
    } finally {
      loading.value = false
    }
  }

  // 搜索医生
  const searchDoctors = (query: string) => {
    searchQuery.value = query
    if (!query) return doctors.value
    
    return doctors.value.filter(doctor => 
      doctor.name.includes(query) ||
      doctor.department.includes(query) ||
      doctor.specialty.some(s => s.includes(query))
    )
  }

  // 按科室筛选
  const filterDoctorsByDepartment = (departmentId: string) => {
    filterDepartment.value = departmentId
    if (!departmentId) return doctors.value
    
    return doctors.value.filter(doctor => doctor.departmentId === departmentId)
  }

  // 按职称筛选
  const filterDoctorsByTitle = (title: string) => {
    filterTitle.value = title
    if (!title) return doctors.value
    
    return doctors.value.filter(doctor => doctor.title === title)
  }

  // 更新医生排班
  const updateDoctorSchedule = async (doctorId: string, schedules: Doctor['schedules']) => {
    loading.value = true
    try {
      const doctor = doctors.value.find(d => d.id === doctorId)
      if (doctor) {
        doctor.schedules = schedules
        return true
      }
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取医生可用时间段
  const getAvailableTimeSlots = (doctorId: string, date: string) => {
    const doctor = doctors.value.find(d => d.id === doctorId)
    if (!doctor) return []
    
    const dayOfWeek = new Date(date).toLocaleDateString('zh-CN', { weekday: 'long' })
    const schedule = doctor.schedules.find(s => s.day === dayOfWeek)
    
    return schedule?.timeSlots.filter(slot => 
      slot.available && slot.currentPatients < slot.maxPatients
    ) || []
  }

  // 预约时间段
  const bookTimeSlot = async (doctorId: string, date: string, timeSlot: string) => {
    loading.value = true
    try {
      const doctor = doctors.value.find(d => d.id === doctorId)
      if (!doctor) throw new Error('医生不存在')
      
      const dayOfWeek = new Date(date).toLocaleDateString('zh-CN', { weekday: 'long' })
      const schedule = doctor.schedules.find(s => s.day === dayOfWeek)
      
      if (schedule) {
        const slot = schedule.timeSlots.find(s => `${s.start}-${s.end}` === timeSlot)
        if (slot && slot.currentPatients < slot.maxPatients) {
          slot.currentPatients++
          return true
        }
      }
      
      throw new Error('时间段不可用')
    } finally {
      loading.value = false
    }
  }

  // 获取统计数据
  const getDoctorStats = () => {
    const total = doctors.value.length
    const byDepartment = doctors.value.reduce((acc, doctor) => {
      acc[doctor.department] = (acc[doctor.department] || 0) + 1
      return acc
    }, {} as Record<string, number>)
    
    const byTitle = doctors.value.reduce((acc, doctor) => {
      acc[doctor.title] = (acc[doctor.title] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const byStatus = doctors.value.reduce((acc, doctor) => {
      acc[doctor.status] = (acc[doctor.status] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const averageExperience = Math.round(
      doctors.value.reduce((sum, doctor) => sum + doctor.experience, 0) / total
    )

    return {
      total,
      byDepartment,
      byTitle,
      byStatus,
      averageExperience
    }
  }

  return {
    doctors,
    currentDoctor,
    searchQuery,
    filterDepartment,
    filterTitle,
    loading,
    getDoctors,
    getDoctorById,
    getDoctorsByDepartment,
    addDoctor,
    updateDoctor,
    deleteDoctor,
    searchDoctors,
    filterDoctorsByDepartment,
    filterDoctorsByTitle,
    updateDoctorSchedule,
    getAvailableTimeSlots,
    bookTimeSlot,
    getDoctorStats
  }
}, {
  persist: {
    key: 'doctor-store',
    storage: localStorage,
    paths: ['doctors']
  }
})